package com.kevin.pro;

import lombok.SneakyThrows;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 生产者消费者测试
 *
 * @author Kevin Liu
 * @since 1.0.0
 */
public class ProduceAncConsumer {

    private final static int MAX_SIZE = 10;

    private final static Lock lock = new NoReentrantLock();

    private final static Condition NOT_EMPTY = lock.newCondition();

    private final static Condition NOT_FULL = lock.newCondition();

    private final static Queue<String> queue = new LinkedBlockingQueue<>();

    public static void main(String[] args) throws Exception {
        Thread producer = new Thread(() -> {
            lock.lock();
            try {
                while (queue.size() == MAX_SIZE) {
                    NOT_FULL.await();
                }
                queue.add("kevin");
                NOT_EMPTY.signalAll();
            } catch (Exception e) {

            } finally {
                lock.unlock();
            }

        });
        Thread consumer = new Thread(() -> {
            lock.lock();
            try {
                while (queue.size() == 0) {
                    NOT_EMPTY.await();
                }
                final String poll = queue.poll();
                System.out.println(poll);
                NOT_FULL.signalAll();
            } catch (Exception e) {

            } finally {
                lock.unlock();
            }

        });
        producer.start();
        consumer.start();
    }

}
